package agent.strategy.strategies;

import agent.strategy.Strategy;
import api.API;
import api.MarketFactory;
import api.MarketType;
import api.betfairAPI.BetfairMarket;
import utils.Display;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * User: Darren
 * Date: 18/05/13
 * Time: 2:37 PM
 */
public class SelectMarketAndViewRepeatedly extends Strategy {
    API api;
    MarketFactory marketFactory;
    Display display;
    ScheduledExecutorService scheduler;
    int intervalInMillis;
    MarketType marketType;

    public SelectMarketAndViewRepeatedly(API api, MarketFactory marketFactory, Display display,
                                  ScheduledExecutorService scheduler, int intervalInSeconds,
                                  MarketType marketType) {
        this.api = api;
        this.marketFactory = marketFactory;
        this.display = display;
        this.scheduler = scheduler;
        this.intervalInMillis = intervalInSeconds * 1000;
        this.marketType = marketType;
    }

    @Override
    public void run() {
        final BetfairMarket market = (BetfairMarket)marketFactory.getMarket(marketType);
        if (api.selectMarket(market, display)) {
            display.displayMarketInfo(market);
            ScheduledFuture<?> scheduledFuture = scheduler.scheduleAtFixedRate(new Runnable() {
                @Override
                public void run() {
                    if (api.getMarketPrices(market)) {
                        display.displayMarketRunners(market);
                    }
                }
            }, 1, 1, TimeUnit.SECONDS);
            try {
                Thread.sleep(intervalInMillis);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            scheduledFuture.cancel(true);
        }
    }
}
